#!/bin/bash
# This file based in part on the mkinitrafms script for the LFS LiveCD
# written by Alexander E. Patrakov and Jeremy Huntwork.
# adapted by Thierry Nuttens for NuTyX

copyFirmwares()
{
  cp -a /lib/firmware/rtlwifi \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/ath6k \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/RTL8192E \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/bnx2x-* \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/brcm \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/iwlwifi-* \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/radeon \
  $WDIR/lib/firmware > /dev/null 2>&1
  cp -a /lib/firmware/ar3k \
  $WDIR/lib/firmware > /dev/null 2>&1
}
copy()
{
  local file

  if [ "$2" == "lib" ]; then
    file=$(PATH=/lib:/usr/lib:/lib/systemd type -p $1)
  else
    file=$(PATH=$PATH:/lib/systemd type -p $1)
  fi

  if [ -n $file ] ; then
	case "$file" in
		/lib/systemd/libsystemd*.so)
			cp $file $WDIR/$2/systemd
			;;
		*)
			cp $file $WDIR/$2
			;;
	esac
  else
    echo "Missing required file: $1 for directory $2"
    rm -rf $WDIR
    exit 1
  fi
}

printf "Creating $INITRAMFS_FILE... \n"
BUSYBOX=`which busybox`
DATADIR=/lib/services
INITIN=init.in

# Create temporaries working directories
WDIR=$(mktemp -d /tmp/initrd-work.XXXXXXXXXX)
unsorted=$(mktemp /tmp/unsorted.XXXXXXXXXX)

# Create base directory structure
# mkdir -p $WDIR/{bin,dev,lib/firmware,run,sbin,sys,proc}
mkdir -p $WDIR/{bin,dev,lib/{lsb,firmware,udev,systemd},run,sbin,sys,proc,tmp,etc,usr/{bin,lib,share}}
mkdir -p $WDIR/etc/{sysconfig,modprobe.d,udev/{rules.d,hwdb.d}}
touch $WDIR/etc/modprobe.d/modprobe.conf
[ -d /lib64 ] && cp -av /lib64 $WDIR/lib64

if [ -z $1 ]; then
	INITRAMFS_FILE=initrd
	KERNEL_VERSION=`basename /lib/modules/*`
else
	KERNEL_VERSION=$1
	if [ -z $BUSYBOX ]; then
		sbinfiles="ip"
	else
		sbinfiles="ip"
	fi
fi

INITRAMFS_FILE=initrd-$1

if [ -n "$KERNEL_VERSION" ] && [ ! -d "/lib/modules/$1" ] ; then
  echo "No modules directory named $1"
  exit 1
fi

libsystemdexecfiles='systemd systemd-sulogin-shell systemd-shutdown systemd-udevd'
usrbinfiles="cut groups"
binfiles="udevadm sh cat clear date grep cp dd hostname killall ls mkdir mknod more mount mountpoint chmod"
binfiles="$binfiles umount stty sed sleep ln rm uname systemd-tmpfiles"

sbinfiles="$sbinfiles blkid switch_root sulogin"

if [ ! -z $1 ]; then

##  Optional files and locations
#
# Add mdadm if present
if [ -x /sbin/mdadm ];then
	if [ -z $BUSYBOX ];then
		sbinfiles="$sbinfiles mdadm"
	else
		cp /sbin/mdadm $WDIR/sbin/mdadm
		ldd /sbin/mdadm | sed "s/\t//" | cut -d " " -f1 >> $unsorted
	fi
fi
#
# Copy the RAID configuration file if present
[ -f /etc/mdadm.conf ] && cp /etc/mdadm.conf $WDIR/etc

#
# Add lvm if present
if [ -x /sbin/lvm ]; then
	if [ -z $BUSYBOX ]; then
		sbinfiles="$sbinfiles lvm dmsetup"
	else
		for I in lvm dmsetup
		do
			cp /sbin/$I $WDIR/sbin/$I
			ldd /sbin/$I | sed "s/\t//" | cut -d " " -f1 >> $unsorted
		done
	fi
	ln -s lvm $WDIR/sbin/lvchange
	ln -s lvm $WDIR/sbin/lvrename
	ln -s lvm $WDIR/sbin/lvextend
	ln -s lvm $WDIR/sbin/lvcreate
	ln -s lvm $WDIR/sbin/lvdisplay
	ln -s lvm $WDIR/sbin/lvscan

	ln -s lvm $WDIR/sbin/pvchange
	ln -s lvm $WDIR/sbin/pvck
	ln -s lvm $WDIR/sbin/pvcreate
	ln -s lvm $WDIR/sbin/pvdisplay
	ln -s lvm $WDIR/sbin/pvscan

	ln -s lvm $WDIR/sbin/vgchange
	ln -s lvm $WDIR/sbin/vgcreate
	ln -s lvm $WDIR/sbin/vgscan
	ln -s lvm $WDIR/sbin/vgrename
	ln -s lvm $WDIR/sbin/vgck

	# Conf file(s)
	cp -a /etc/lvm $WDIR/etc
fi
#
# Add cryptsetup if present
if [ -x /sbin/cryptsetup ]; then
	[[ -f /etc/crypttab ]] && cp /etc/crypttab $WDIR/etc/crypttab
	if [ -z $BUSYBOX ]; then
		sbinfiles="$sbinfiles cryptsetup"
	else
		cp /sbin/cryptsetup $WDIR/sbin/cryptsetup
		ldd /sbin/cryptsetup | sed "s/\t//" | cut -d " " -f1 >> $unsorted
	fi
	if [ -f /root/.crypto/keyfile.bin ]; then
		mkdir -p $WDIR/root/.crypto
		cp /root/.crypto/keyfile.bin $WDIR/root/.crypto
	fi
fi
fi
# Create necessary device nodes
# mknod -m 640 $WDIR/dev/console c 5 1
# mknod -m 664 $WDIR/dev/null    c 1 3

# Install the init-functions
[ -f /lib/lsb/init-functions ] && cp /lib/lsb/init-functions $WDIR/lib/lsb/init-functions
[ -n "$KERNEL_VERSION" ] && cp /etc/group $WDIR/etc

cat > $WDIR/etc/fstab << "EOF"
# Begin /etc/fstab

# nfs mountpoint example
# 192.168.254.254:/home/thierry/devel /home/thierry/devel nfs rw,vers=3,_netdev,rsize=8192,wsize=8192 0 0
proc       /proc    proc     nosuid,noexec,nodev 0     0
sysfs      /sys     sysfs    nosuid,noexec,nodev 0     0
devpts     /dev/pts devpts   gid=5,mode=620      0     0
tmpfs      /run     tmpfs    defaults            0     0
devtmpfs   /dev     devtmpfs mode=0755,nosuid    0     0
EOF

# echo and false are a bit wird
if [ -z $BUSYBOX ];then
	cp /bin/echo $WDIR/bin/echo
	cp /bin/false $WDIR/bin/false
else
	cp $BUSYBOX $WDIR/$BUSYBOX
	ln -s $BUSYBOX $WDIR/bin/echo
	ln -s $BUSYBOX $WDIR/bin/false

fi
# terminal stuff
mkdir -p $WDIR/usr/share/terminfo/l
cp /usr/share/terminfo/l/linux \
 $WDIR/usr/share/terminfo/l/

# Install the udev configuration files if needed
if [ ! -z $1 ]; then
	[ -f /etc/udev/udev.conf ] && cp /etc/udev/udev.conf $WDIR/etc/udev/udev.conf
	for file in $(find /etc/udev/rules.d/ -type f) ; do
		cp $file $WDIR/etc/udev/rules.d
	done
	for file in $(find /etc/udev/hwdb.d/ -type f) ; do
		cp $file $WDIR/etc/udev/hwdb.d
	done
	cat > $WDIR/etc/udev/rules.d/55-lfs.rules << "EOF"
# /etc/udev/rules.d/55-lfs.rules: Rule definitions for LFS.

# Core kernel devices

# This causes the system clock to be set as soon as /dev/rtc becomes available.
SUBSYSTEM=="rtc", ACTION=="add", MODE="0644", RUN="do_start_clock"
KERNEL=="rtc", ACTION=="add", MODE="0644", RUN="do_start_clock"

# Comms devices

KERNEL=="ippp[0-9]*",       GROUP="dialout"
KERNEL=="isdn[0-9]*",       GROUP="dialout"
KERNEL=="isdnctrl[0-9]*",   GROUP="dialout"
KERNEL=="dcbri[0-9]*",      GROUP="dialout"
EOF
fi
# Hostname
if [ -f /etc/hostname ] ; then
	cp /etc/hostname $WDIR/etc/hostname
else
	echo "yaolinux" > $WDIR/etc/hostname
fi
# Clock setting
[ -f /etc/sysconfig/clock ] && cp /etc/sysconfig/clock $WDIR/etc/sysconfig

# Install any firmware present
# cp -a /lib/firmware $WDIR/lib

# Install the init file
install -m0755 $DATADIR/$INITIN $WDIR/init

if [ -x /bin/kmod ] ; then
	binfiles="$binfiles kmod"
else
	binfiles="$binfiles lsmod"
	sbinfiles="$sbinfiles insmod"
fi

# Install basic binaries
for f in $usrbinfiles; do
	if [ -z $BUSYBOX ]; then
		ldd /usr/bin/$f | sed "s/\t//" | cut -d " " -f1 >> $unsorted
		copy $f usr/bin
	else
		ln -s $BUSYBOX $WDIR/usr/bin/$f
	fi
done

for f in $binfiles ; do
	if [ -z $BUSYBOX ]; then
		ldd /bin/$f | sed "s/\t//" | cut -d " " -f1 >> $unsorted
		copy $f bin
	else
		ln -s $BUSYBOX $WDIR/bin/$f
	fi
done

for f in $sbinfiles ; do
	if [ -z $BUSYBOX ];then
		ldd /sbin/$f | sed "s/\t//" | cut -d " " -f1 >> $unsorted
		copy $f sbin
	else
		ln -s $BUSYBOX $WDIR/sbin/$f
	fi
done

for f in $libsystemdexecfiles ; do
	if [ -z $BUSYBOX ];then
		ldd /lib/systemd/$f | sed "s/\t//" | cut -d " " -f1 >> $unsorted
		copy $f lib/systemd
	else
		ln -s -v $BUSYBOX $WDIR/lib/systemd/$f
	fi
done


if [ -z $BUSYBOX ]; then
	if [ -x /bin/kmod ] ; then
		ln -s kmod $WDIR/bin/lsmod
		ln -s ../bin/kmod $WDIR/sbin/insmod
		ln -s ../bin/kmod $WDIR/sbin/modprobe
		ln -s ../bin/kmod $WDIR/sbin/depmod
	fi
else
	ln -s $BUSYBOX $WDIR/sbin/insmod
	ln -s $BUSYBOX $WDIR/sbin/modprobe
	ln -s $BUSYBOX $WDIR/sbin/depmod
	ln -s $BUSYBOX $WDIR/bin/lsmod
fi


# Install libraries
sort $unsorted | uniq | while read library ; do
  if [ "$library" == "linux-vdso.so.1" ] ||
     [ "$library" == "linux-gate.so.1" ]; then
    continue
  fi

  copy $library lib
done
if [ ! -z $1 ]; then
	cp -a /lib/udev $WDIR/lib

# The Hardware clock setting maybe could be faster done
	cat > $WDIR/lib/udev/do_start_clock << "EOF"
#!/bin/sh -e
. /lib/lsb/init-functions
do_start_clock
EOF
	chmod 755 $WDIR/lib/udev/do_start_clock
fi
#
# Install requested  kernel modules

mods=(dm-mod md-mod ehci-pci \
xhci-pci xhci-hcd vfat fat nls_cp437 \
ehci-hcd uhci-hcd uas nls_iso8859-1 \
usbcore usb-common usb-storage loop sr_mod \
cdrom squashfs isofs overlay mmc_core \
rtsx_pci rtsx_pci_sdmmc rtsx_pci_ms mmc_block \
ssb lpc_ich shpcp sdhci-acpi sdhci-pltfm \
sdhci sdhci-pci \
serio i8042 libps2 atkbd)

if [ "${2}" != "-nf" ] ||  [ "${2}" != "--no-firmwares" ];then
                for i in /sys/module/*; do mods+=($(basename $i)); done
fi

sorted_mods=($(echo ${mods[@]} | tr ' ' '\n' | sort -u))

for i in ${sorted_mods[@]}
do
	find /lib/modules/$KERNEL_VERSION/ -type f -name $i* 2> /dev/null | \
	cpio --make-directories -p --quiet $WDIR 2> /dev/null
done

if [ ! -z $1 ]; then
	find \
	/lib/modules/$KERNEL_VERSION/kernel/drivers/md \
	-type f 2> /dev/null | cpio --make-directories -p --quiet $WDIR 2> /dev/null

	if [ "${2}" == "-nf" ] ||  [ "${2}" == "--no-firmwares" ];then
		printf "No firmware copied, it's for an ISO.\n"
	else
		copyFirmwares
	fi
fi

cp /lib/modules/$KERNEL_VERSION/modules.{builtin,order,symbols} \
$WDIR/lib/modules/$KERNEL_VERSION

depmod -a -b $WDIR $KERNEL_VERSION

rm -f /boot/$INITRAMFS_FILE

( cd $WDIR ; find . | cpio -o -H newc --quiet | gzip -9 ) > $INITRAMFS_FILE

# Remove the temporary direc
rm -rf $WDIR $unsorted
mv $INITRAMFS_FILE /boot/$INITRAMFS_FILE

if [ -d /ISO ];then
	mkdir -p /ISO/boot
	cp -v /boot/kernel-$1 /ISO/boot/
	cp -v /boot/initrd-$1 /ISO/boot/
fi

printf "done.\n"

